import { createDraftSafeSelector } from "@reduxjs/toolkit";
import { getTenantId } from "@common/utils";

export const getWarehouseCandidates = createDraftSafeSelector(
  (state) => state.userProfile.allWarehouses,
  (state) => state.userProfile.defaultScenario,
  (allWarehouses, defaultScenario) => {
    if (allWarehouses) {
      if (defaultScenario) {
        let selected = defaultScenario.map((i) => i.id);
        let candidates = allWarehouses.filter((i) => !selected.includes(i.id));
        return [candidates.map((i) => ({ label: i.name, value: i.id }))];
      } else {
        return [allWarehouses.map((i) => ({ label: i.name, value: i.id }))];
      }
    }
    return [];
  }
);

export const getSelectedWarehouses = createDraftSafeSelector(
  (state) => state.userProfile.defaultScenario,
  (defaultScenario) => {
    if (defaultScenario) {
      return [defaultScenario.map((i) => ({ label: i.name, value: i.id }))];
    }
    return [[]];
  }
);

export const getTenantList = createDraftSafeSelector(
  (state) => state.userProfile.userTenants,
  (userTenants) => {
    let result = [];
    if (userTenants && userTenants.length > 0) {
      userTenants.forEach((i) => {
        result.push({
          id: i.tenant.id,
          name: i.tenant.name
        });
      });
    }
    return result;
  }
);

export const getTenantInfo = createDraftSafeSelector(
  (state) => state.userProfile.userTenants,
  (state) => state.globalState.token,
  (userTenants, token) => {
    let result = {};
    if (userTenants && userTenants.length > 0) {
      let tenantId = getTenantId(token);
      let tenant = userTenants.filter((i) => i.tenantId === tenantId);
      result = tenant[0].tenant;
    }
    return result;
  }
);